package v1

import (
	"gin-example/models"
	"gin-example/pkg/e"
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"
	"log"
	"net/http"
	"strconv"
)

func GetAllContents(c *gin.Context) {
	data := make(map[string]interface{})
	code := e.SUCCESS

	data["lists"] = models.GetContents()

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"data": data,
	})
}

func GetContentsByOffset(c *gin.Context) {
	data := make(map[string]interface{})
	code := e.SUCCESS
	limit := []int{0, 10}

	pageStr := c.DefaultQuery("page", "1")
	sizeStr := c.DefaultQuery("size", "10")

	if tmp, err := strconv.Atoi(sizeStr); err == nil {
		limit[1] = tmp
	}

	if tmp, err := strconv.Atoi(pageStr); err == nil {
		limit[0] = (tmp - 1) * limit[1]
	}

	data["total"], data["lists"] = models.GetContentsByOffset(limit)

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"data": data,
	})
}

func AddContent(c *gin.Context) {
	json := make(map[string]string)
	_ = c.BindJSON(&json)

	title := json["title"]
	tag := json["tag"]
	content := json["content"]
	i18n := json["i18n"]
	top := json["top"]
	createAt := json["create_at"]

	valid := validation.Validation{}
	valid.Required(title, "title").Message("标题不能为空")
	valid.Required(tag, "tag").Message("标签不能为空")
	valid.Required(content, "content").Message("内容不能为空")
	valid.Required(i18n, "i18n").Message("语言不能为空")
	valid.Required(top, "top").Message("是否置顶不能为空")
	valid.Required(createAt, "createAt").Message("创建日期不能为空")
	code := e.INVALID_PARAMS
	if !valid.HasErrors() {
		code = e.SUCCESS
		tmp1, _ := strconv.Atoi(top)
		tmp2, _ := strconv.ParseInt(createAt, 10, 64)
		models.AddContent(title, tag, content, i18n, tmp1, tmp2)
	} else {
		for _, err := range valid.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"data": make(map[string]string),
	})
}

func UpdateContent(c *gin.Context) {
	id := com.StrTo(c.Param("id")).MustInt()
	code := e.INVALID_PARAMS

	if models.ExistContentByID(id) {
		code = e.SUCCESS
		json := make(map[string]interface{})
		_ = c.BindJSON(&json)
		top := json["top"]
		createAt := json["create_at"]
		tmp1, _ := strconv.Atoi(top.(string))
		tmp2, _ := strconv.ParseInt(createAt.(string), 10, 64)

		json["top"] = tmp1
		json["create_at"] = tmp2

		models.UpdateContent(id, json)
	} else {
		code = e.ERROR_NOT_EXIST
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"data": make(map[string]string),
	})
}

func DeleteContent(c *gin.Context) {
	id := com.StrTo(c.Param("id")).MustInt()
	code := e.INVALID_PARAMS
	if models.ExistContentByID(id) {
		models.DeleteContent(id)
		code = e.SUCCESS
	} else {
		code = e.ERROR_NOT_EXIST
	}
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"data": make(map[string]string),
	})
}